﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Web;

namespace AiXiu.WebSite
{
    /// <summary>
    /// 图片上传处理程序
    /// </summary>
    public class ImageUploadHandler : IHttpHandler
    {
        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            // 读取参数
            int length = int.Parse(context.Request.QueryString["length"] ?? "0");
            if (length <= 0)
            {
                context.Response.StatusCode = 400;
                context.Response.End();
                return;
            }
            // 读取编码流长度
            int rsLen = (int)context.Request.InputStream?.Length;
            if (rsLen <= 0)
            {
                context.Response.StatusCode = 400;
                context.Response.End();
                return;
            }
            // 尝试存储
            byte[] base64Bytes = new byte[context.Request.InputStream.Length];
            context.Request.InputStream.Seek(0, SeekOrigin.Begin);
            context.Request.InputStream.Read(base64Bytes, 0, base64Bytes.Length);
            string base64String = Encoding.Default.GetString(base64Bytes);
            // 判断是否完整接收
            if (base64String?.Length == length)
            {
                base64String = base64String.Substring(base64String.IndexOf("base64") + 7);
                byte[] baseByte = Convert.FromBase64String(base64String);
                // 保存到文件
                string randomString = Guid.NewGuid().ToString("N");
                string fileName = $"{context.Server.MapPath("~/avatar")}/{randomString}.jpg";
                string fileUrl = $"/avatar/{randomString}.jpg";
                using (MemoryStream memoryStream = new MemoryStream(baseByte))
                {
                    using (Image image = Image.FromStream(memoryStream))
                    {
                        image.Save(fileName, ImageFormat.Jpeg);
                    }
                }
                context.Response.Write(fileUrl);
                context.Response.End();
            }
            else
            {
                context.Response.StatusCode = 400;
                context.Response.End();
                return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}